#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2018/4/11 14:35
# @Author  : simple0426
# @Email   : istyle.simple@gmail.com
# @File    : backup_check.py
# @Software: PyCharm
# @desc    : 此脚本主要检测备份文件是否存在

import datetime
import os
from istyle_mail import Mail
import re, random
import paramiko

def check_backup(sub_dir, name):
    flag = False
    if os.path.exists(sub_dir):
        obj_list = os.listdir(sub_dir)
        if name in obj_list:
            flag = True
    return flag
f = open('backup_check.log', 'a')
# 生产备份检测
online_backup_dir = os.path.join(os.path.expanduser('~'), 'online_data_backup', 'backup')
online_backup_name = datetime.datetime.now().strftime('%Y-%m-%d')
mail = Mail('he@abc.com', '******', 'smtp.qiye.163.com', smtp_port=465, ssl=True)

if not check_backup(online_backup_dir, online_backup_name):
    f.write('%s %s not exists' % (online_backup_dir, online_backup_name))
    print('%s %s not exists' % (online_backup_dir, online_backup_name))
else:
    mail.bind_obj('MySQL数据备份%s下的%s存在<br>' % (online_backup_dir, online_backup_name))


# gitlab备份检测
gitlab_dir = os.path.join(os.path.expanduser('~'), 'gitlab', 'gitdata_backup')
if os.path.exists(gitlab_dir):
    filename = random.choice(os.listdir(gitlab_dir))
today = datetime.datetime.now().strftime('%Y_%m_%d')
filename_match = re.compile(r'(\d{10}_%s_gitlab_backup.tar)' % today)
if not filename_match.match(filename):
    f.write('%s %s not exists' % (gitlab_dir, filename))
    print('%s %s not exists' % (gitlab_dir, filename))
else:
    mail.bind_obj('gitlab数据备份%s下的%s存在<br>' % (gitlab_dir, filename))

# showdoc备份检测
hostname = '10.10.10.243'
username = 'dell'
password = '123456789'

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(hostname=hostname, username=username, password=password)
stdin, stdout, stderr = ssh.exec_command('ls ~/java/java06/backup')

filename_list = stdout.readlines()
today = datetime.datetime.now().strftime('%Y-%m-%d')
today_file = 'showdoc.db.php-' + today

if today_file + '\n' in filename_list:
    mail.bind_obj('showdoc数据备份%s下的%s存在<br>' % ('~/java/java06/backup', today_file))
else:
    f.write('%s %s not exists' % ('~/java/java06/backup', today_file))
    print('%s %s not exists' % ('~/java/java06/backup', today_file))

ssh.close()
f.close()

mail.sendmail('备份检测', 'abc@qq.com')
